<?php
namespace App\Http\Controllers\Api\Mall;

use App\Http\Controllers\Controller;
use App\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class OrderController extends Controller
{
    /**
     * @function 订单列表
     *
     * @param Request $request
     * @return $this
     */
    public function orderList(Request $request)
    {
        $user = auth()->user();

        $orders = Order::where('user_id', $user->id)->orderBy('id', 'desc')->where('status', 1)->paginate(10);
        foreach ($orders as $order) {
            foreach ($order->items as $item) $item->Products;
        }

        return response()->json(['code' => 1000, 'data' => $orders])->withCallback($request->input('callback'));
    }

    /**
     * @function 订单详情
     *
     * @param Request $request
     * @return $this
     */
    public function orderDetail(Request $request)
    {
        $user = auth()->user();
        $order = Order::where('user_id', $user->id)->where('id', $request->input('id'))->first();
        foreach ($order->items as $item) $item->Products;

        return response()->json(['code' => 1000, 'data' => $order])->withCallback($request->input('callback'));
    }

    /**
     * @function 更新订单数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderUpdate(Request $request)
    {
        $user = auth()->user();

        $id = $request->input('id');
        $order = Order::findOrFail($id);
        if ($order->user_id != $user->id) {
            return response()->json(['code' => 1000, 'msg' => 'order error']);
        }

        $fields = ['realname', 'phone', 'address', 'remark'];
        foreach ($fields as $field) {
            if ($request->has($field)) {
                $order->$field = $request->input($field);
            }
        }

        try {
            DB::beginTransaction();

            $order->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json(['code' => 9000, 'msg' => $e->getMessage()]);
        }

        return response()->json(['code' => 1000, 'msg' => 'ok']);
    }
    
}